import React, {useRef, useEffect, useState} from "react";
import {history, useParams, connect} from 'umi';
import {useAccess} from '@umijs/max';
import {cloneDeep} from "lodash";
import {ActionType, PageContainer, ProTable} from '@ant-design/pro-components';
import {DatePicker, Tag} from 'antd';
import request from "@/utils/request";
import days from "dayjs";


const {RangePicker} = DatePicker;
const AccessPage: React.FC = (props: any) => {
    const {dispatch, searchState} = props;
    const {location: {state = {}} = {}} = history;
    const proTableFormRef: any = useRef();
    console.log('state', state)
    const actionRef = useRef<ActionType>();
    const [stationList, setList] = useState([])
    useEffect(() => {
        const rangeDate = searchState?.startTime && searchState?.endTime ? [days(searchState?.startTime), days(searchState?.endTime)] :
            state?.startTime && state?.endTime ? [days(state?.startTime), days(state?.endTime)] : null;
        proTableFormRef.current.setFieldsValue({
            // pileCode: searchState?.pileCode || state?.pileCode,
            // gunCode: searchState?.gunCode ? searchState?.gunCode : state?.gunCode ? state?.gunCode.startsWith('1') ? parseInt(state?.gunCode) : parseInt(state?.gunCode.slice(-1)) : undefined,
            // vin: searchState?.vin ? searchState.vin : state?.vin || undefined,
            // selfOrder: searchState?.selfOrder ? searchState.selfOrder : state?.selfOrder.toString() || undefined,
            ...searchState,
            createTime: rangeDate,

        })
    }, [dispatch]);
    useEffect(() => {
        request('/api1/baseFunction/stationPageList', {
            method: 'post',
            data: {
                pageNum: 1,
                pageSize: 9999
            }
        }).then((res) => {
            console.log('全部站', res);
            if (res && res.code === 200) {
                setList(res?.data?.records || [])
            }
        })
    }, [dispatch]);
    const stationEnum: any = {};
    if (stationList && stationList.length) {
        for (const d of stationList) {
            stationEnum[d.id] = {text: d.stationName}
        }
    }
    console.log('stationEnum', stationEnum);
    const columns: any = [
        {
            title: '所属场站',
            dataIndex: 'stationId',
            key: 'stationId',
            // search: false,
            valueEnum: stationEnum,
            render: (_, record) => {
                return (<span>{record?.stationName || ''}</span>)
            }
        },
        {
            title: '订单编号',
            dataIndex: 'orderNum',
            key: 'orderNum',
        },
        {
            title: '桩编号',
            dataIndex: 'pileCode',
            key: 'pileCode',
            // search: false,
        },
        {
            title: '枪号',
            dataIndex: 'gunCode',
            key: 'gunCode',
            // search: false,
        },
        {
            title: '订单来源',
            dataIndex: 'selfOrder',
            key: 'selfOrder',
            hideInTable: true,
            valueEnum: {
                0: {text: '小桔'},
                1: {text: '本平台'},
            },
            // hideInSearch: true,
            // search: false,
            // show
        },
        {
            title: '订单状态',
            dataIndex: 'status',
            key: 'status',
            // search: false,
            valueEnum: {
                0: {text: '充电中'},
                1: {text: '已完成'},
                2: {text: '启动失败'},
            },
            render: (_, record) => {
                // console.log('text', text)
                const text = record?.status;
                return (
                    <div>{text === 0 ? <Tag color="#2db7f5">充电中</Tag> : text === 1 ?
                        <Tag color="#87d068">已完成</Tag> : <Tag color="#f50">启动失败</Tag>}</div>
                )
            }
        },
        {
            title: '充电电量',
            dataIndex: 'chargeCapacity',
            key: 'chargeCapacity',
            search: false,
            render: (text) => {
                return (
                    <div>{text || '0.00'}</div>
                )
            }
        },
        {
            title: '充电时长',
            dataIndex: 'duration',
            key: 'duration',
            search: false,
            render: (text) => {
                return (
                    <div>{text || '0'}</div>
                )
            }
        },
        {
            title: 'vin',
            dataIndex: 'vin',
            key: 'vin',
            // search: false,
        },
        {
            title: '充电时间',
            dataIndex: 'createTime',
            key: 'createTime',
            // search: false,
            renderFormItem: () => {
                // let list = [{"id": 0, "name": "Nginx大全"}, {"id": 1, "name": "Java从入门到精通"}]
                // // let list = Array.from(selectEnum);
                // const options = list.map(item => <option key={item.id}>{item.name}</option>);
                return (
                    <RangePicker placeholder={['起始时间', '截止时间']} showTime/>
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'ope',
            search: false,
            render: (_, record) => {
                return (
                    <a onClick={() => history.push('/order/chargeOrder/detail', {
                        orderId: record.id
                    })} style={{color: '#316ad5'}}>详情</a>
                )
            }
        },
    ]
    return (
        <PageContainer
            ghost
            header={{
                title: '',
            }}
        >
            <ProTable<API.UserInfo>
                headerTitle="订单列表"
                actionRef={actionRef}
                rowKey="id"
                pagination={{defaultPageSize: 10, pageSize: searchState.pageSize, current: searchState.pageNum}}
                search={{
                    labelWidth: 120,
                    defaultCollapsed: false
                }}
                formRef={proTableFormRef}
                // params={{...tableParams, current: tableParams.pageNum,  pileCode: state?.pileCode,}}
                request={async (params, sorter, filter) => {
                    // const { data, success } = await queryUserList({
                    //   ...params,
                    //   // FIXME: remove @ts-ignore
                    //   // @ts-ignore
                    //   sorter,
                    //   filter,
                    // });
                    // return {
                    //   data: data?.list || [],
                    //   success,
                    // };
                    // const cloneParams = cloneDeep({...params, ...proTableFormRef.current.getFieldsValue()  });
                    // delete cloneParams.current;
                    const tableParams = {...params, ...proTableFormRef.current.getFieldsValue()};
                    console.log('tableParams', tableParams);
                    const cloneParams = cloneDeep(tableParams);
                    delete cloneParams.current;
                    delete cloneParams.createTime;
                    if (tableParams.createTime && tableParams.createTime.length) {
                        cloneParams.startTime = days(tableParams.createTime[0]).format('YYYY-MM-DD HH:mm:ss');
                        cloneParams.endTime = days(tableParams.createTime[1]).format('YYYY-MM-DD HH:mm:ss');
                    }
                    const {data, code} = await request('/api1/monitorDevice/orderPageList', {
                        method: 'post',
                        data: {
                            ...cloneParams,
                            gunCode: cloneParams.gunCode ?  parseInt(cloneParams.gunCode) : null,
                            pageNum: params.current
                        }
                    });
                    dispatch({
                        type: 'order/setState',
                        payload: {
                            searchState: {
                                ...cloneParams,
                                gunCode: cloneParams.gunCode ?  parseInt(cloneParams.gunCode) : null,
                                pageNum: params.current
                            }
                        }
                    })
                    console.log('data', data);
                    if (code && code === 200) {
                        return {
                            data: data?.records || [],
                            success: true,
                            total: data?.total
                        };
                    }
                }}
                columns={columns}
                // onChange={(pagination) => {
                //     console.log('分页内容', pagination);
                //     console.log('roTableFormRef.current.pileCode', proTableFormRef.current.getFieldValue('pileCode'));
                //     console.log('roTableFormRef.current.orderNum', proTableFormRef.current.getFieldValue('orderNum'));
                //     setParams({
                //         pageSize: pagination?.pageSize,
                //         pageNum: pagination?.current,
                //         pileCode: proTableFormRef.current.getFieldValue('pileCode'),
                //         orderNum: proTableFormRef.current.getFieldValue('orderNum'),
                //     })
                // }}
            />
        </PageContainer>
    );
};

export default connect(({order}) => {
    return {...order}
})(AccessPage);
